//
//  InputTextViewController.m
//  RomensUISDK
//
//  Created by 裴飞杨 on 2018/4/10.
//  Copyright © 2018年 Romens. All rights reserved.
//

#import "InputTextViewController.h"
#import <Masonry/Masonry.h>

#define hintYOffset -200

@interface InputTextViewController () <UITextViewDelegate>{
    NSString *_inputType;
    //是否是必填项
    BOOL _isMustInput;
    //整数和小数模式下，是否开启输入限制(最大值，最小值)
    BOOL _minMaxType;
    //正则表达式检测
    BOOL _textSpecialExpType;
}

@property (nonatomic,strong) UIView *textViewBackView;
@property (nonatomic,strong) UITextView *inputTextView;
@property (nonatomic,strong) UILabel *limitLabel;

//限制最大字数
@property (nonatomic,copy)NSString *maxLength;
//限制最小字数
@property (nonatomic,copy)NSString *minLength;
//可输入的最小值
@property (nonatomic,strong)NSNumber *minValue;
//可输入的最大值
@property (nonatomic,strong)NSNumber *maxValue;
//小数模式下，保留的小数位数
@property (nonatomic, assign)int decimalPlace;
//文本输入检测特殊字符相关
@property (nonatomic, copy)NSString *textSpecialHint;   //提示内容
@property (nonatomic, copy)NSString *textSpecialExp;    //正则表达式
@end

@implementation InputTextViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatInputTextUI];
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.inputTextView becomeFirstResponder];
}

-(void)creatInputTextUI {
    [self.mainBackGroundView addSubview:self.textViewBackView];
    [self.textViewBackView addSubview:self.inputTextView];
    
    NSDictionary *views = NSDictionaryOfVariableBindings(_textViewBackView, _inputTextView);
    [self.mainBackGroundView addConstraints:[ToolHelper GetNSLayoutCont:views format:@"H:|[_textViewBackView]|"]];
    [self.mainBackGroundView addConstraints:[ToolHelper GetNSLayoutCont:views format:@"V:|[_textViewBackView(100)]|"]];
    
    [self.textViewBackView addConstraints:[ToolHelper GetNSLayoutCont:views format:@"H:|[_inputTextView]|"]];
    [self.textViewBackView addConstraints:[ToolHelper GetNSLayoutCont:views format:@"V:|[_inputTextView]-5-|"]];
    
    //最大输入长度提示 0/max
    if (!isEmptyString(self.maxLength)) {
        [self.textViewBackView addSubview:self.limitLabel];
        [self.limitLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.right.equalTo(self.inputTextView).insets(UIEdgeInsetsMake(0, 0, 5, 5));
            make.height.mas_equalTo(10);
        }];
    }
    //提示限制内容
    if (!isEmptyString(self.textSpecialHint)) {
        self.msgLabel.text = [NSString stringWithFormat:@"%@ %@", self.msgLabel.text, self.textSpecialHint];
    }
}
#pragma mark -输入完成
-(void)inputDone {
    NSString *errorStr = [self detectionInputText];
    if (!isEmptyString(errorStr)) {
        [self showHint:errorStr yOffset:hintYOffset];
        return;
    }
    if (self.inputDoneBlock) {
        self.inputDoneBlock(self.inputTextView.text);
    }
    [super inputDone];
}
#pragma mark - 检测

/**
 输入文本是否符合规定。

 @return 符合规定:@"",反之:错误信息
 */
-(NSString *)detectionInputText {
    NSString *inputStr = self.inputTextView.text;
    //非空
    if (isEmptyString(inputStr)) {
        return @"请输入内容";
    }
    //最小长度
    if (!isEmptyString(self.minLength)) {
        return (inputStr.length < [self.minLength intValue])? [NSString stringWithFormat:@"最少录入%@字，请继续输入", self.minLength]: @"";
    }
    //小数位数
    if ([_inputType isEqualToString:DECIMAL_TYPE]) {
        bool is = [self validateInputValueByRegExp:inputStr withRegex:[NSString stringWithFormat:@"^[0-9]+(\\.[0-9]{1,%d})?$", self.decimalPlace]];
        if (!is) {
            return @"输入不合法，请输入正确的小数";
        }
    }
    //最大值，最小值判断
    if (_minMaxType) {
        NSNumber *inputNum = @([inputStr doubleValue]);
        //小于最小值，大于最大值，返回@""
        if ([inputNum compare:self.minValue] == NSOrderedAscending || [inputNum compare:self.maxValue] == NSOrderedDescending) {
            return [NSString stringWithFormat:@"输入不合法，输入范围是: %@ - %@", self.minValue, self.maxValue];
        }
    }
    return @"";
}

#pragma mark - TextView delegate
//监听每次的输入
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]){ //按下完成
        [textView resignFirstResponder];
        [self inputDone];
        return NO;
    }
    NSString *inputStr = [textView.text stringByReplacingCharactersInRange:range withString:text];
    //当前录入长度大于最大录入值时，就录入不上了
    if (!isEmptyString(self.maxLength) && inputStr.length > [self.maxLength intValue]) {
        return NO;
    }
    //当前只录入纯数字
    if ([_inputType isEqualToString:INT_TYPE]) {
        return [self validateInputValueByRegExp:inputStr withRegex:@"^[0-9]*$"];
    }
    //录入小数
    if ([_inputType isEqualToString:DECIMAL_TYPE]) {
        //{0,%d}, 0或n次
        return [self validateInputValueByRegExp:inputStr withRegex:[NSString stringWithFormat:@"^[0-9]+(\\.[0-9]{0,%d})?$", self.decimalPlace]];
    }
    return YES;
}

//监听输入结束
-(void)textViewDidChange:(UITextView *)textView {
    NSString *inputStr = textView.text;
    UITextRange *selectedRange = [textView markedTextRange];
    UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];//获取高亮部分
    //开启正则表达式检测 && 有输入内容 && 不符合正则表达式
    if (_textSpecialExpType && inputStr.length > 0 && !position && ![self validateInputValueByRegExp:inputStr withRegex:self.textSpecialExp]) {
        self.inputTextView.text = [inputStr substringToIndex:inputStr.length - 1];
    }
    //最大输入长度
    if (!isEmptyString(self.maxLength)) {
        [self reloadLimitLabel:inputStr.length];
    }
}
//限制输入方法
- (BOOL)validateInputValueByRegExp:(NSString*)string withRegex:(NSString *)regex {
    BOOL isValid = YES;
    NSUInteger len = string.length;
    if (len > 0) {
        NSPredicate *numberPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        isValid = [numberPredicate evaluateWithObject:string];
    }
    return isValid;
}

#pragma mark - 更新限制输入长度
-(void)reloadLimitLabel:(int)length {
    self.limitLabel.text = [NSString stringWithFormat:@"%d/%@", length, self.maxLength];
}

#pragma mark - 重写GET SET方法
-(void)setModel:(InputCellModel *)model {
    [super setModel:model];
    self.inputTextView.text = model.inputDetail;
    self.inputTextView.selectedRange = NSMakeRange(0, model.inputDetail.length);
    self.inputTextView.keyboardType = model.keyboardType;
    _isMustInput = model.isMustInput;
    //最大录入长度
    if ([model.maxLength intValue] != 0) {
        self.maxLength = model.maxLength;
        [self reloadLimitLabel:model.inputDetail.length];
    }
    //最小录入长度(不为空且值不为0时，增加限制)
    if (!isEmptyString(model.minLength) && [model.minLength intValue] != 0) {
        self.minLength = model.minLength;
    }
    _inputType = model.inputtype;
    if ([_inputType isEqualToString:TEXT_TYPE] || [_inputType isEqualToString:TEXT_MULTI_TYPE]) {
        //正则表达式检测
        if (!isEmptyString(model.textSpecialExp) && !isEmptyString(model.textSpecial)) {
            _textSpecialExpType = YES;
            self.textSpecialHint = model.textSpecial;
            self.textSpecialExp = model.textSpecialExp;
        }
    }
    if ([_inputType isEqualToString:INT_TYPE] || [_inputType isEqualToString:DECIMAL_TYPE]) {
        //最大值、最小值
        if (!isEmptyString(model.minValue) && !isEmptyString(model.maxValue)) {
            _minMaxType = YES;
            self.minValue = @([model.minValue doubleValue]);
            self.maxValue = @([model.maxValue doubleValue]);
        }
        //保留位数
        if (!isEmptyString(model.decimalPlace)) {
            _decimalPlace = [model.decimalPlace intValue];
        }
    }
}

-(int)decimalPlace {
    if (!_decimalPlace) {
        _decimalPlace = 50;
    }
    return _decimalPlace;
}

#pragma mark - 懒加载控件
-(UIView *)textViewBackView {
    if (!_textViewBackView) {
        _textViewBackView = [[UIView alloc]init];
        _textViewBackView.backgroundColor = [UIColor whiteColor];
        _textViewBackView.translatesAutoresizingMaskIntoConstraints = NO;
        [_textViewBackView.layer setBorderColor:RGB(211, 211, 211).CGColor];
        [_textViewBackView.layer setBorderWidth:0.5];
        [_textViewBackView.layer setCornerRadius:4];
    }
    return _textViewBackView;
}
-(UITextView *)inputTextView {
    if (!_inputTextView) {
        _inputTextView = [[UITextView alloc]init];
        _inputTextView.font = systemDefaultFont;
        _inputTextView.returnKeyType = UIReturnKeyDone;
        _inputTextView.delegate = self;
        _inputTextView.translatesAutoresizingMaskIntoConstraints = NO;
    }
    return _inputTextView;
}
-(UILabel *)limitLabel {
    if (!_limitLabel) {
        _limitLabel = [[UILabel alloc] init];
        _limitLabel.font = systemDetailFont;
        _limitLabel.textColor = [UIColor lightGrayColor];
    }
    return _limitLabel;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

//- (void)createAlertController {
//    [self.inputTextView resignFirstResponder];
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.textSpecialHint preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        [self dismissViewControllerAnimated:YES completion:nil];
//        [self.inputTextView becomeFirstResponder];
//    }];
//    [alert addAction:action];
//    [self presentViewController:alert animated:YES completion:nil];
//}

//    _textSpecialExpType = YES;
//    self.textSpecialExp = @"(^[\\u4e00-\\u9fa5]+$)|(^[a-zA-Z\\s]+$)";
//    NSString *lang = [[UIApplication sharedApplication] textInputMode].primaryLanguage; // 键盘输入模式
//    [lang isEqualToString:@"zh-Hans"]//中文输入法
@end
